package com.example.shirospringboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.example.shirospringboot.config.UserNamePasswordToken;
import com.example.shirospringboot.config.WrapperSysUser;
import com.example.shirospringboot.model.SysUser;
import com.example.shirospringboot.requestBean.UserNamePasswordBean;
import com.example.shirospringboot.util.JWTUtil;

@Controller
public class LoginController {
    @Autowired
    private JWTUtil jwtUtil;
    
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody UserNamePasswordBean userNamePasswordBean) {
        UserNamePasswordToken userNamePasswordToken = new UserNamePasswordToken();
        userNamePasswordToken.setUserName(userNamePasswordBean.getUsername());
        userNamePasswordToken.setPassword(userNamePasswordBean.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(userNamePasswordToken);
    
        //生成 token并返回
        WrapperSysUser wrapperSysUser = (WrapperSysUser) subject.getPrincipal();
        SysUser sysUser = wrapperSysUser.getSysUser();
        Integer userid = sysUser.getUserid();
        String token = jwtUtil.getToken(userid, sysUser.getPassowrd());
        return ResponseEntity.ok(token);
    }
}
